﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Web;

namespace CommonCodeManagers.plugin
{
    public class HttpHandler
    {
        public static string Get(string Url)
        {
            //string Url = string.Format(@"http://www.baidu.com?key=abc");
            //GET
            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(Url);
                req.Method = "GET";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Timeout = 3000;//单位毫秒

                WebResponse wr = req.GetResponse();
                Stream rs = wr.GetResponseStream();
                Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                StreamReader rsp = new StreamReader(rs, encode);
                string rsp_cnt = rsp.ReadToEnd();
                rsp.Close();
                return rsp_cnt;
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误信息:\r\n" + ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return string.Empty;
        }

        public static string Post(string Url,Dictionary<string,string> param,string charset="UTF-8")
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(Url);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded; charset=" + charset;
                req.Timeout = 30000000;
                //添加参数
                string req_params = string.Empty;
                foreach (var key in param.Keys)
                {
                    req_params += (string.IsNullOrEmpty(req_params) ? "" : "&") + key + "=" + System.Web.HttpUtility.UrlEncode(param[key]);
                }

                req.ContentLength = req_params.Length;
                Stream reqStream = req.GetRequestStream();
                byte[] bs = Encoding.ASCII.GetBytes(req_params);
                reqStream.Write(bs, 0, bs.Length);

                WebResponse wr = req.GetResponse();
                Stream rs = wr.GetResponseStream();
                Encoding encode = System.Text.Encoding.GetEncoding(charset);
                StreamReader rsp = new StreamReader(rs, encode);
                string rsp_cnt = rsp.ReadToEnd();
                rsp.Close();
                return rsp_cnt;
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误信息:\n" + ex.Message + "\r\n" + ex.StackTrace, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return string.Empty;
        }
    }
}